/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package sopraim.presenter.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jboss.weld.servlet.SessionHolder;
import sopraim.entity.Status;
import sopraim.entity.User;
import sopraim.model.Model;
import sopraim.model.UserDAO;

/**
 * Auto complete form fields (for searching)
 * validate username when creating user
 * and send all the status to the client
 * @author info A1
 */
@WebServlet(name="AutoCompleteServlet",
        urlPatterns = {
            "/autocomplete",
            "/checkUsername",
            "/checkPassword"
        })
public class AutoCompleteServlet extends HttpServlet {
    
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String userPath = request.getServletPath();
        PrintWriter out= response.getWriter();
        //autocomplete the username fields (for search purpose)
        switch (userPath) {
            case "/autocomplete":
            {
                //get the typed characters
                String query = request.getParameter("term");
                UserDAO userFacade = Model.getInstance().getUserDAO();
                //get the usernames that match the typed characters
                List<String> usernames = getData(userFacade.findAllUsernames(), query);
                //send the results in json format
                JsonArrayBuilder json = Json.createArrayBuilder();
                Iterator<String> iterator = usernames.iterator();
                while(iterator.hasNext()) {
                    String username = (String)iterator.next();
                    json.add(username);
                }       JsonArray array = json.build();
                out.print(array);
                out.flush();
                out.close();
                break;
            }
            case "/checkUsername":
            {
                //get the username to check
                String username = request.getParameter("username");
                //get all the existing usernames
                UserDAO userFacade = Model.getInstance().getUserDAO();
                List<String> allUsers = userFacade.findAllUsernames();
                boolean isUnique = !allUsers.contains(username);
                JsonObject valid = Json.createObjectBuilder()
                        .add("valid", isUnique)
                        .build();
                out.print(valid);
                out.flush();
                out.close();
                break;
            }
            case "/checkPassword":
            {
                String passwd = request.getParameter("password");
                User user = ((User)request.getSession().getAttribute("user"));
                
                boolean isValid = user.checkPassword(passwd);
                JsonObject valid = Json.createObjectBuilder()
                        .add("valid", isValid)
                        .build();
                out.print(valid);
                out.flush();
                out.close();
                break;
            }
      
        }
        
    }
    
    /**
     * get the list of usernames that matches a request
     * @param query
     * @param data
     * @return
     */
    private List<String> getData(List<String> data, String query ) {
        String username ;
        query = query.toLowerCase();
        List<String> matched = new ArrayList<>();
        for(int i=0; i<data.size(); i++) {
            username = data.get(i).toLowerCase();
            if(username.startsWith(query)) {
                matched.add(data.get(i));
            }
        }
        return matched;
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
}
